<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

if (!function_exists('get_middle_str')) {
    /**
     * 获取指定字符串中间内容
     * @param string $str 原字符串
     * @param string $leftStr 左侧
     * @param string $rightStr
     * @return bool|string
     */
    function get_middle_str($str, $leftStr, $rightStr)
    {
        $left  = strpos($str, $leftStr);
        $right = strpos($str, $rightStr, $left);
        if ($left < 0 || $right < $left) {
            return '';
        }
        return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
    }
}


if (!function_exists('format_size')) {
    /**
     * 格式化文件大小单位
     * @param $size
     * @param string $delimiter
     * @return string
     */
    function format_size($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 5; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}
    /* PHP不使用速算扣除数计算个人所得税
   * @param float $salary 含税收入金额
   * @param float $deduction 保险等应当扣除的金额 默认值为0
   * @param float $threshold 起征金额 默认值为5000
   * @return float | false 返回值为应缴税金额 参数错误时返回false
  */

function getPersonalIncomeTax($salary, $deduction=0, $threshold=5000){

    if(!is_numeric($salary) || !is_numeric($deduction) || !is_numeric($threshold)){

        return false;

    }

    if($salary <= $threshold){

        return 0;

    }

    $levels = array(3000, 12000, 25000, 35000, 55000, 80000, PHP_INT_MAX);

    $rates = array(0.03, 0.1, 0.2, 0.25, 0.3, 0.35, 0.45);

    $taxableIncome = $salary - $threshold - $deduction;

    $tax = 0;

    foreach($levels as $k => $level){

        $previousLevel = isset($levels[$k-1]) ? $levels[$k-1] : 0;

        if($taxableIncome <= $level){

            $tax += ($taxableIncome - $previousLevel) * $rates[$k];

            break;

        }

        $tax += ($level-$previousLevel) * $rates[$k];

    }

    $tax = round($tax, 2);

    return $tax;

}
